﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//------------------------------------------------------------
// shaco Framework
// Copyright © 2017-2025 chang.liu All rights reserved.
// Feedback: 449612236@qq.com
//------------------------------------------------------------

namespace shaco
{
    public class SpriteAtlasHelper
    {
        SpriteAtlasHelper() { }

        static SpriteAtlasHelper instance
        {
            get
            {
                if (null == _instance)
                {
                    _instance = new();
                }
                return _instance;
            }
        }
        static SpriteAtlasHelper _instance;

        Queue<KeyValuePair<string, System.Action<UnityEngine.U2D.SpriteAtlas>>> _atlasRequests = new();
        System.Action<string, System.Action<UnityEngine.U2D.SpriteAtlas>> _callbackLoad;

        //图集请求初始化，该方法一定要在整个项目启动最早时候就调用，否则atlasRequested请求可能有丢失
        static public void Init()
        {
            Debug.Log("SpriteAtlasHelper Init");

#if UNITY_2017_1_OR_NEWER
            UnityEngine.U2D.SpriteAtlasManager.atlasRequested -= instance.OnAtlasRequested;
            UnityEngine.U2D.SpriteAtlasManager.atlasRequested += instance.OnAtlasRequested;
#else
            shaco.Log.Error("SpriteAtlasManager Init error: only support on Unity2017 or upper !");
#endif
        }

        //绑定图集请求回调
        static public void SetAtlasRequestedCallBack(System.Action<string, System.Action<UnityEngine.U2D.SpriteAtlas>> callbackLoad)
        {
            instance._callbackLoad = callbackLoad;

            foreach (var iter in instance._atlasRequests)
            {
                callbackLoad(iter.Key, iter.Value);
            }
            instance._atlasRequests.Clear();
        }

        void OnAtlasRequested(string atlasName, System.Action<UnityEngine.U2D.SpriteAtlas> callbackLoadEnd)
        {
            if (null == _callbackLoad)
                _atlasRequests.Enqueue(new(atlasName, callbackLoadEnd));
            else
                instance._callbackLoad(atlasName, callbackLoadEnd);
        }
    }
}